package com.huitone.smspfm.core.signal;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;

import com.bin.common.utils.StringUtils;
import com.bin.common.utils.SystemUtils;
import com.huitone.smspfm.context.app.AppManager;
import com.huitone.smspfm.logger.ExtLogger;

import sun.misc.Signal;
import sun.misc.SignalHandler;

/**   
* @Title SimpleAppStatusListener.java 
* @Package com.huitone.smspfm.interfacz.core.signal 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年9月15日 下午6:41:43 
* @version V1.0   
*/
@SuppressWarnings("restriction")
public class SimpleAppStatusListener implements SignalHandler {
	
	private static final ExtLogger logger = ExtLogger.create(SimpleAppStatusListener.class);
	
	Properties properties = new Properties();
	
	private AppStatusListener listener = null;
	
	public SimpleAppStatusListener(AppStatusListener listener) {
		
		this.listener = listener;
		
		start();
	}

	@Override
	public void handle(Signal signal) {
		
		if (properties.containsKey("smspfm.reload.signal."+signal.getNumber())) {
			
			if (AppManager.isRunning()) {
				
				AppManager.reloading();
				
				if (listener != null) listener.reload();
				
				AppManager.running();
				
			} else {
				logger.info("短信平台预处理程序已经关闭!");
			}
		}
		
		if (properties.containsKey("smspfm.stop.signal."+signal.getNumber())) {
			
			AppManager.shutdown();
			
			if (listener != null) listener.stop();
		}
		
		if (properties.containsKey("smspfm.rebuild.signal."+signal.getNumber())) {
			
			if (listener != null) listener.rebuild();
		}
	}

	public void start() {
		
		AppManager.starting();
		
		try {
			properties.load(getClass().getResourceAsStream(File.separator +"signal" + File.separator 
					+ "signal_" + StringUtils.toString(SystemUtils.getSystemAgname()) + ".properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Iterator<Entry<Object, Object>> iterator = properties.entrySet().iterator();
		while(iterator.hasNext()) {
			
			Entry<Object, Object> entry = iterator.next();
			String key = StringUtils.toString(entry.getKey());
			String value = StringUtils.toString(entry.getValue());
			
			if (!StringUtils.startsWith(key, "smspfm.reload.signal")) {
				Signal.handle(new Signal(value), this);
			}
			
			if (!StringUtils.startsWith(key, "smspfm.stop.signal")) {
				Signal.handle(new Signal(value), this);
			}
			
			if (!StringUtils.startsWith(key, "smspfm.rebuild.signal")) {
				Signal.handle(new Signal(value), this);
			}
		}
		
		if (listener != null) {
			listener.start();
		}
		
		AppManager.running();
	}
	
}
